﻿
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Web;
using System.Text;
using System.Collections;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Business;

namespace YiYiTong.Rocket.Web.Controllers
{
    public class WechatController : ApiController
    {
        /// <summary>
        /// 微信支付结果通知
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        public HttpResponseMessage Notify()
        {
            WxNotityRespModel respModel = new WxNotityRespModel();
            respModel.return_code = "FAIL";
            respModel.return_msg = "NO";
            if (HttpContext.Current.Request.InputStream.Length != 0)
            {
                using (StreamReader sReader = new StreamReader(HttpContext.Current.Request.InputStream))
                {
                    string data = sReader.ReadToEnd();
                    Hashtable retHt = Utils.StrToXml(data);
                    LogHelper.Info("微信支付结果通知," + data);

                    string returnCode = Utils.GetHtValue(retHt, "return_code");
                    string returnMsg = Utils.GetHtValue(retHt, "return_msg");
                    if (returnCode == "SUCCESS")
                    {
                        string key = ConfigHelper.AppSetting<string>("wx_md5key");
                        //签名验证
                        if (Utils.CheckSign(retHt, key))
                        {
                            string resultCode = Utils.GetHtValue(retHt, "result_code");
                            if (resultCode == "SUCCESS")
                            {
                                decimal total_fee = ConvertHelper.ConvertTo<decimal>(Utils.GetHtValue(retHt, "total_fee"));
                                decimal amt = total_fee / 100;   //订单总金额，单位为分
                                string out_trade_no = Utils.GetHtValue(retHt, "out_trade_no");                  //商户订单号
                                string transaction_id = Utils.GetHtValue(retHt, "transaction_id");              //微信支付订单号	

                                long order_master_id = 0;  //支付订单id
                                int business_order_type = 0;//1 销售订单 2竞价报名订单
                                //验证完成,开始处理业务逻辑
                                if (OrderBiz.Instance.ChargeOrderSucc(out_trade_no, transaction_id, amt, out order_master_id, out business_order_type))
                                {
                                    respModel.return_code = "SUCCESS";
                                    respModel.return_msg = "OK";

                                    if (order_master_id > 0)
                                    {
                                        if (business_order_type == (int)BusinessOrderType.SaleOrder)
                                        {
                                            //支付订单付款
                                            if (!OrderBiz.Instance.OrderPaySucc(order_master_id, (int)PayType.Wechat))
                                            {
                                                respModel.return_code = "FAIL";
                                                respModel.return_msg = "FAIL";
                                            }
                                        }
                                        else if (business_order_type == (int)BusinessOrderType.BaomingOrder)
                                        {
                                            //竞价报名订单付款
                                            if (!JingjiaBiz.Instance.BaomingPaySucc(order_master_id, (int)PayType.Wechat))
                                            {
                                                respModel.return_code = "FAIL";
                                                respModel.return_msg = "FAIL";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                            LogHelper.Error("微信支付结果通知,签名验证失败");
                    }
                }
            }

            string strReturn = Utils.ToCDATAXml(respModel);
            return GetReturn(strReturn);
        }

        /// <summary>
        /// 微信退款结果通知
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        public HttpResponseMessage RefundNotify()
        {
            WxNotityRespModel respModel = new WxNotityRespModel();
            respModel.return_code = "FAIL";
            respModel.return_msg = "NO";
            if (HttpContext.Current.Request.InputStream.Length != 0)
            {
                using (StreamReader sReader = new StreamReader(HttpContext.Current.Request.InputStream))
                {
                    string data = sReader.ReadToEnd();
                    Hashtable retHt = Utils.StrToXml(data);
                    LogHelper.Info("微信退款结果通知," + data);

                    string returnCode = Utils.GetHtValue(retHt, "return_code");
                    string returnMsg = Utils.GetHtValue(retHt, "return_msg");
                    if (returnCode == "SUCCESS")
                    {
                        string req_info = Utils.GetHtValue(retHt, "req_info"); //加密信息
                        /* 解密步骤
                         *（1）对加密串A做base64解码，得到加密串B
                         *（2）对商户key做md5，得到32位小写key* ( key设置路径：微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 )
                         *（3）用key*对加密串B做AES-256-ECB解密（PKCS7Padding）*/
                        req_info = Utils.DecodeBase64(req_info);
                        string key = Utils.Md5Encrypt(ConfigHelper.AppSetting<string>("wx_md5key"), Encoding.UTF8).ToLower();
                        string decData = AES.Decrypt(req_info, key);
                        if (!string.IsNullOrWhiteSpace(decData))
                        {
                            Hashtable reqInfoHt = Utils.StrToXml(decData, "root");
                            string out_trade_no = Utils.GetHtValue(reqInfoHt, "out_trade_no");      //商户订单号
                            string out_refund_no = Utils.GetHtValue(reqInfoHt, "out_refund_no");    //商户退款订单号
                            string refund_id = Utils.GetHtValue(reqInfoHt, "refund_id");            //微信退款单号

                            //退款状态 SUCCESS-退款成功 CHANGE - 退款异常 REFUNDCLOSE—退款关闭
                            string refund_status = Utils.GetHtValue(reqInfoHt, "refund_status");
                            //退款金额
                            decimal refund_fee = ConvertHelper.ConvertTo<decimal>(Utils.GetHtValue(reqInfoHt, "refund_fee")) / 100;


                            //解密完成，开始处理业务逻辑 toding
                        }
                        else
                            LogHelper.Error("微信退款结果通知,AES解密失败");
                    }
                }
            }

            string strReturn = Utils.ToCDATAXml(respModel);
            return GetReturn(strReturn);
        }

        private HttpResponseMessage GetReturn(string str)
        {
            HttpResponseMessage resp = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/xml") };
            return resp;
        }
    }
}
